using EPiServer.Core;
using System.Web.UI;
using EPiServer;
using EPiSugar.Content;
using EPiSugar.Markup;

namespace EPiSugar.Web.UI
{
    /// <summary>
    /// Convenience base class for accessing EPiSugar functionality.
    /// </summary>
    /// <typeparam name="T">The type of entity this user control handles.</typeparam>
    public abstract class EntityUserControl<T> : UserControlBase where T: class 
    {
        protected virtual ContentGenerator Content
        {
            get { return new ContentGenerator(Page, FindPageSource(this)); }
        }

        protected virtual TagGenerator Tags
        {
            get { return new TagGenerator(Page); }
        }

        private EntityAdapter.EntityContext<T> entity;
        protected EntityAdapter.EntityContext<T> Entity
        {
            get { return entity ?? (entity = new EntityAdapter.EntityContext<T>(Current.Model, FindPageSource(NamingContainer))); }
            set { entity = value; }
        }

        private IPageSource FindPageSource(Control current)
        {
            if(current == null) return null;
            return current as IPageSource ?? FindPageSource(current.NamingContainer);
        }
    }
}
